package 深度优先_广度优先;

public class LeetCode200_岛屿数量 {
    public int[][] nextP = {{1,0},{-1,0},{0,1},{0,-1}};

    public void dfs(char[][] grid, int row, int col) {

        grid[row][col] = '0';
        for(int i = 0; i < 4; i++) {
            int ni = row + nextP[i][0];
            int nj = col + nextP[i][1];
            if(ni < 0 || ni >= grid.length || nj < 0 || nj >= grid[0].length) {
                continue;
            }
            if(grid[ni][nj] == '1') {
                dfs(grid,ni,nj);
            }
        }

    }

    public int numIslands(char[][] grid) {
        if(grid.length == 0) {
            return 0;
        }
        int row = grid.length;
        int col = grid[0].length;
        int sum = 0;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(grid[i][j] == '1') {
                    sum ++;
                    dfs(grid, i, j);
                }
            }
        }
        return sum;
    }
}
